package com.gitee.chili.leisure.util;

import com.gitee.chili.leisure.ResponseCode;
import com.gitee.chili.leisure.core.Packet;
import com.gitee.chili.leisure.model.BaseMessageModel;
import com.gitee.chili.leisure.model.MessageCmdEnum;
import io.netty.channel.Channel;

import java.util.Objects;

/**
 * MessageUtil
 *
 * @author week solider
 * @since 2020.08.31
 */
public class AuxiliaryChannel {


    /**
     * 写回客户端异常消息
     *
     * @param channel 当前消息信道
     * @param errCmd  异常的指令
     * @param res     错误类型
     */
    public static ResponseCode errorMessage(Channel channel, MessageCmdEnum.Command errCmd, ResponseCode res) {
        BaseMessageModel.Error.Builder builder = BaseMessageModel.Error.newBuilder();
        builder.setCmd(errCmd);
        builder.setCode(res.getCode());
        builder.setMessage(res.getValue());
        channel.writeAndFlush(Packet.newPacket(MessageCmdEnum.Command.ERROR, builder.build().toByteArray()));
        return res;
    }

    /**
     * 写回客户端异常消息
     *
     * @param channel 当前消息信道
     * @param cmd     异常的指令
     */
    public static BaseMessageModel.Error errorMessage(Channel channel, MessageCmdEnum.Command cmd, Integer code, String msg) {
        BaseMessageModel.Error.Builder builder = BaseMessageModel.Error.newBuilder();
        builder.setCmd(cmd);
        builder.setCode(code);
        builder.setMessage(msg);
        if (Objects.nonNull(channel)) {
            channel.writeAndFlush(Packet.newPacket(MessageCmdEnum.Command.ERROR, builder.build().toByteArray()));
        }
        return builder.build();
    }

    /**
     * {@link #errorMessage(Channel, MessageCmdEnum.Command, Integer, String)}
     */
    public static BaseMessageModel.Error errorMessage(MessageCmdEnum.Command cmd, Integer code, String msg) {
        return errorMessage(null, cmd, code, msg);
    }
}
